package net.xdclass.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.controller.req.FileUpdateReq;
import net.xdclass.controller.req.FolderCreateReq;
import net.xdclass.dto.AccountFileDTO;
import net.xdclass.enums.BizCodeEnum;
import net.xdclass.enums.FolderFlagEnum;
import net.xdclass.exception.BizException;
import net.xdclass.mapper.AccountFileMapper;
import net.xdclass.mapper.FileMapper;
import net.xdclass.model.AccountFileDO;
import net.xdclass.service.AccountFileService;
import net.xdclass.utils.SpringBeanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class AccountFileServiceImpl implements AccountFileService {

    @Autowired
    private AccountFileMapper accountFileMapper;

    @Autowired
    private FileMapper fileMapper;



    /**
     * 获取文件列表接口
     * @param accountId
     * @param parentId
     * @return
     */
    @Override
    public List<AccountFileDTO> listFile(Long accountId, Long parentId) {

        List<AccountFileDO> accountFileDOList = accountFileMapper.selectList(new QueryWrapper<AccountFileDO>().eq("account_id", accountId).eq("parent_id", parentId)
                .orderByDesc("is_dir").orderByDesc("gmt_create"));

        return SpringBeanUtil.copyProperties(accountFileDOList, AccountFileDTO.class);
    }

    /**
     * 1.检查id是否存在
     * 2.新旧文件名称不能一样
     * 3.同层文件名不能一样
     * @param req
     */
    @Override
    public void renameFile(FileUpdateReq req) {
        AccountFileDO accountFileDO = accountFileMapper.selectOne(new QueryWrapper<AccountFileDO>()
                .eq("account_id", req.getAccountId()).eq("id",req.getFileId()));

        if(Objects.isNull(accountFileDO)){
            log.error("文件不存在,{}",req.getFileId());
            throw new BizException(BizCodeEnum.FILE_NOT_EXISTS);
        }else {
            if(Objects.equals(accountFileDO.getFileName(),req.getFileName())){
                log.error("文件名重复,{}",req);
                throw new BizException(BizCodeEnum.FILE_RENAME_REPEAT);
            }
            //同层文件名称不能一样
            Long selectCount = accountFileMapper.selectCount(new QueryWrapper<AccountFileDO>()
                    .eq("account_id", req.getAccountId()).eq("parent_id", accountFileDO.getParentId())
                    .eq("file_name", req.getFileName()));
            if (selectCount > 0){
                log.error("文件名重复:{}",req);
                throw new BizException(BizCodeEnum.FILE_RENAME_REPEAT);
            }else {
                accountFileDO.setFileName(req.getNewFileName());
                accountFileMapper.updateById(accountFileDO);
            }
        }
    }

    /**
     * 创建文件夹
     * @param folderCreateReq
     */
    @Override
    public Long createFolder(FolderCreateReq folderCreateReq) {
        AccountFileDTO accountFileDTO = AccountFileDTO.builder().accountId(folderCreateReq.getAccountId())
                .parentId(folderCreateReq.getParentId())
                .fileName(folderCreateReq.getFolderName())
                .isDir(FolderFlagEnum.YES.getCode())
                .build();
        return saveAccountFile(accountFileDTO);
    }

    /**
     * 处理用户和文件的映射关系
     * 1.检查父文件是否存在
     * 2.检查文件是否重名
     * 3.保存相关文件关系
     * @param accountFileDTO
     * @return
     */
    private Long saveAccountFile(AccountFileDTO accountFileDTO) {
        checkParentFileId(accountFileDTO);
        AccountFileDO accountFileDO = SpringBeanUtil.copyProperties(accountFileDTO, AccountFileDO.class);
        proccessFileNameDuplicate(accountFileDO);
        accountFileMapper.insert(accountFileDO);
        return accountFileDO.getId();
    }

    /**
     * 处理文件是否重复
     * @param accountFileDO
     */
    private void proccessFileNameDuplicate(AccountFileDO accountFileDO) {
        Long count = accountFileMapper.selectCount(new QueryWrapper<AccountFileDO>().eq("account_id", accountFileDO.getAccountId())
                .eq("parent_id", accountFileDO.getParentId()).eq("is_dir", accountFileDO.getIsDir())
                .eq("file_name", accountFileDO.getFileName()));
        if(count>0){
            //处理重复文件夹
            if(Objects.equals(accountFileDO.getIsDir(),FolderFlagEnum.YES.getCode())){
                accountFileDO.setFileName(accountFileDO.getFileName()+"(1)");
            }else{
                //处理重复文件名
                String[] split = accountFileDO.getFileName().split("\\.");
                accountFileDO.setFileName(split[0]+"(1)."+split[1]);

            }

        }
    }

    /**
     * 检查父文件是否存在
     * @param accountFileDTO
     */
    private void checkParentFileId(AccountFileDTO accountFileDTO) {
        if(accountFileDTO.getParentId() != 0){
            AccountFileDO accountFileDO = accountFileMapper.selectOne(new QueryWrapper<AccountFileDO>().eq("id", accountFileDTO.getParentId()));
            if(accountFileDO == null){
                throw new BizException(BizCodeEnum.FILE_NOT_EXISTS);
            }
        }
    }
}
